package great.easychat.help;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.lifecycle.Observer;

import com.umeng.commonsdk.UMConfigure;

import great.easychat.help.activity.MainNewActivity;
import great.easychat.help.bean.CommonModel;
import great.easychat.help.bean.ConfigBean;
import great.easychat.help.bean.UserInfoBean;
import great.easychat.help.dialog.PhonePemissionDialog;
import great.easychat.help.dialog.ProtocolDialog;
import great.easychat.help.uinque.SharedPerferencesUtil;
import great.easychat.help.uinque.UUIDUtils;
import great.easychat.help.util.DebugLog;
import great.easychat.help.util.ToastUtil;
import great.easychat.help.util.UserInfoManger;
import great.easychat.help.viewModel.SplashViewModel;

import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED;
import static great.easychat.help.Constant.UMENG_CHANNEL;
import static great.easychat.help.Constant.UMENG_KEY;

// 开屏页，相关逻辑结合了登录页面
public class SplashActivity extends BaseActivity<SplashViewModel> implements PhonePemissionDialog.Callback {

    String uniqueId;

    @Override
    protected void observeLiveData() {
        /**
         * 获取配置
         * 检查是否已经注册
         * 进行注册
         * 登录并缓存用户信息
         */
        viewModel.getHostConfigLiveData().observe(this, new Observer<ConfigBean>() {
            @Override
            public void onChanged(ConfigBean configBean) {
                UserInfoManger.config = configBean;
                // 注册 登录
                uniqueId = UUIDUtils.getInstance().getUniqueID(getApplicationContext());
                DebugLog.d("uniqueId1->" + uniqueId);
                viewModel.getUserInfo(uniqueId);
            }
        });

        viewModel.getUserInfoLiveData().observe(this, new Observer<UserInfoBean>() {
            @Override
            public void onChanged(UserInfoBean userInfoBean) {
                UserInfoManger.update(userInfoBean);
                startApp();
            }
        });

        viewModel.getAddUserInfoLiveData().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isOk) {
                if (isOk) {
                    viewModel.getUserInfo(uniqueId);
                } else {
                    ToastUtil.show("数据异常，请重启App");
                }
            }
        });
    }

    @Override
    protected boolean isToolBarEnable() {
        return false;
    }

    private void startApp() {
        Intent intent = new Intent(SplashActivity.this, MainNewActivity.class);
        startActivity(intent);
        finish();
    }


    @Override
    protected void onActivityCreateStart() {
        super.onActivityCreateStart();
        // 解决在安装器中打开APP后，当APP从后台回到前台时，会重新启动的bug
        // 参考:https://blog.csdn.net/fantasy_lin_/article/details/80152257
        if (!isTaskRoot() && getIntent() != null) {
            String action = getIntent().getAction();
            if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                finish();
                return;
            }
        }
    }

    @Override
    public void setViewData(Bundle savedInstanceState) {
        // 判断是否同意了用户协议
        boolean isRead = (boolean) SharedPerferencesUtil.getInstance(this).getData("pro", false);
        if (!isRead) {
            ProtocolDialog protocolDialog = new ProtocolDialog();
            protocolDialog.show(this, new ProtocolDialog.Callback() {
                @Override
                public void onClickAgree() {
                    UMConfigure.init(getApplication(), UMENG_KEY, UMENG_CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, "");
                    SharedPerferencesUtil.getInstance(SplashActivity.this).putData("pro", true);
                    getPermissions();
                }

                @Override
                public void onClickReject() {
                    System.exit(0);
                }
            });
        } else {
            UMConfigure.init(getApplication(), UMENG_KEY, UMENG_CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, "");
            getPermissions();
        }
    }

    @Override
    public int requestLayoutId() {
        return R.layout.activity_splash;
    }

    // 请求权限
    private void getPermissions() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, 0);
    }

    PhonePemissionDialog phonePemissionDialog;

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PERMISSION_GRANTED &&
                    PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PERMISSION_GRANTED) {
                DebugLog.d("uniqueId onRequestPermissionsResult->" + uniqueId);
                viewModel.getConfig();
            } else {
                ToastUtil.show("为了启动App，请授予相关权限");
                if (phonePemissionDialog == null) {
                    phonePemissionDialog = new PhonePemissionDialog();
                }
                phonePemissionDialog.show(this, this);
            }
        }
    }

    // 授权弹框消失说明已经拿到了权限，开始初始化
    @Override
    public void dismiss() {
        DebugLog.d("uniqueId dismiss->" + uniqueId);
        viewModel.getConfig();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (phonePemissionDialog != null) {
            phonePemissionDialog.refresh();
        }
    }

}
